package com.doctorpda.compresser;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Reader;
import java.io.Writer;

import com.yahoo.platform.yui.compressor.CssCompressor;
import com.yahoo.platform.yui.compressor.JavaScriptCompressor;

/**
 * 递归压缩js/css
 * @author guixi.lee
 *
 */
public class JsCssCompressor {
	// 要处理的目录
	//File dir = new File("E:\\zsyx_study");

	int linebreakpos = -1;
	boolean munge = true;
	boolean verbose = false;
	boolean preserveAllSemiColons = false;
	boolean disableOptimizations = false;
	
	// 压缩文件数量
	int jsCount = 0;
	int cssCount = 0;

	public static void main(String[] args) {
		if (args.length > 0){
			JsCssCompressor c = new JsCssCompressor();
			File dir = new File(args[0]);
			c.checkFile(dir);
			System.out.println("共压缩js/css文件 "+(c.jsCount+c.cssCount)+"个，其中：js文件 "+(c.jsCount)+"个，css文件 "+(c.cssCount)+"个");
		} else {
			System.out.println("请输入压缩路径");
		}
		
	}

	/**
	 * 递归压缩js/css
	 * @param file
	 * @throws Exception
	 */
	public void checkFile(File file) {
		if (file.isFile() && (file.getName().endsWith(".css") || file.getName().endsWith(".js"))) {
			try {
				compressor(file);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return;
		}
		
		if (file.isDirectory()){
			File[] files = file.listFiles();
			for (File f : files) {
				checkFile(f);
			}
		}
		
	}

	/**
	 * 执行压缩
	 * @param file
	 * @throws Exception
	 */
	public void compressor(File file) throws Exception {
		String fileName = file.getName();
		String filePath = file.getAbsolutePath();
		
		// System.out.print(filePath + "\t");
		Reader in = new FileReader(file);
		
		File tempFile = new File(filePath + ".temp");
		Writer out = new FileWriter(tempFile);
		if (fileName.endsWith(".js")) {
			/*JavaScriptCompressor jscompressor = new JavaScriptCompressor(in, new YuiCompressorErrorReporter());*/
			JavaScriptCompressor jscompressor = new JavaScriptCompressor(in, new YuiCompressorErrorReporter());
			
			jscompressor.compress(out, linebreakpos, munge, verbose,
					preserveAllSemiColons, disableOptimizations);
			jsCount ++;
		} else if (fileName.endsWith(".css")) {
			CssCompressor csscompressor = new CssCompressor(in);
			csscompressor.compress(out, linebreakpos);
			cssCount ++;
		}

		System.out.print("\t 已压缩.");
		System.out.println();
		out.close();
		in.close();
		file.delete();
		tempFile.renameTo(file);
		tempFile.delete();
	}
	
	/**
     * 压缩JS文件
     */
    public static void compressJS(String yuiPath, StringBuilder sb, File f, String encoding) {
        if (f.isDirectory()) {
            File[] files = f.listFiles();
            // 如果某个文件夹是空文件夹，则跳过
            if (files == null) {
                return;
            }
            for (File file : files) {
                compressJS(yuiPath, sb, file, encoding);
            }
        } else {
            String fileName = f.getName();
            if (fileName.endsWith(".js") && !fileName.endsWith("-min.js")) {
                sb.append("java -jar ");
                sb.append(yuiPath);
                sb.append(" --type js --charset ");
                sb.append(encoding + " " + f.getPath());
                sb.append(" -o " + f.getPath().replace(".js", "-min.js"));
                sb.append("\n");
            }
        }
    }
 
    /**
     * 压缩CSS文件
     */
    public static void compressCSS(String yuiPath, StringBuilder sb, File f, String encoding) {
        if (f.isDirectory()) {
            File[] files = f.listFiles();
            // 如果某个文件夹是空文件夹，则跳过
            if (files == null) {
                return;
            }
            for (File file : files) {
                compressCSS(yuiPath, sb, file, encoding);
            }
        } else {
            String fileName = f.getName();
            if (fileName.endsWith(".css") && !fileName.endsWith("-min.css")) {
                sb.append("java -jar ");
                sb.append(yuiPath);
                sb.append(" --type css --charset ");
                sb.append(encoding + " " + f.getPath());
                sb.append(" -o " + f.getPath().replace(".css", "-min.css"));
                sb.append("\n");
            }
        }
    }

	public int getLinebreakpos() {
		return linebreakpos;
	}

	public void setLinebreakpos(int linebreakpos) {
		this.linebreakpos = linebreakpos;
	}

	public boolean isMunge() {
		return munge;
	}

	public void setMunge(boolean munge) {
		this.munge = munge;
	}

	public boolean isVerbose() {
		return verbose;
	}

	public void setVerbose(boolean verbose) {
		this.verbose = verbose;
	}

	public boolean isPreserveAllSemiColons() {
		return preserveAllSemiColons;
	}

	public void setPreserveAllSemiColons(boolean preserveAllSemiColons) {
		this.preserveAllSemiColons = preserveAllSemiColons;
	}

	public boolean isDisableOptimizations() {
		return disableOptimizations;
	}

	public void setDisableOptimizations(boolean disableOptimizations) {
		this.disableOptimizations = disableOptimizations;
	}

	public int getJsCount() {
		return jsCount;
	}

	public void setJsCount(int jsCount) {
		this.jsCount = jsCount;
	}

	public int getCssCount() {
		return cssCount;
	}

	public void setCssCount(int cssCount) {
		this.cssCount = cssCount;
	}
	
	
}
